source ./load-dotenv.sh

if [ ! -d $WG_ROOT_CONFIG_FOLDER ]; then
  echo "Creating root config folder...";
  mkdir $WG_ROOT_CONFIG_FOLDER;
fi

if [ ! -f $WG_ROOT_CONFIG_FOLDER/privatekey ]; then
  echo "Generating private key...";
  wg genkey | tee $WG_ROOT_CONFIG_FOLDER/privatekey | wg pubkey > $WG_ROOT_CONFIG_FOLDER/publickey;
fi

export WG_ROOT_PRIVATE_KEY=$(cat $WG_ROOT_CONFIG_FOLDER/privatekey);

# read config from wg0.conf.in and expand the variables inside it
# and write it to wg0.conf
if [ ! -f $WG_SUBNET_ADDR/wg0.conf ]; then
  echo "Generating wg0.conf...";
  envsubst < wg0.conf.in > $WG_ROOT_CONFIG_FOLDER/wg0.conf;
fi

sudo cp $WG_ROOT_CONFIG_FOLDER/* /etc/wireguard/